from django.shortcuts import render
from pymysql import IntegrityError

from order.models import OrderModel,OrderDetialModel
from rest_framework.views import APIView
from rest_framework.response import Response
from order.orser import OrderSerializer, OrderDetialSerializer
from rest_framework.viewsets import ModelViewSet
from utils.myredis import redistoll
import random
import time
from django.db import transaction
from cart.models import CartModel
from rest_framework.generics import ListAPIView
from cart.cartser import CartSerializer
from user.models import UserModel
from user.userser import UserSerializer

# Create your views here.
class CartView(ListAPIView):
    queryset = CartModel.objects.all()
    serializer_class = CartSerializer
    def get_queryset(self):
        user = self.request.query_params.get('user')
        if user:
            return self.queryset.filter(user=user,select=True)
class UserCore(APIView):
    def get(self, request):
        user = request.GET.get('user')
        ser = UserModel.objects.get(id=user)
        ser = UserSerializer(ser)
        return Response({"message":"获取成功","code":200,'data':ser.data})
def get_order_num():
    order_num = "T" + str(time.strftime("%Y%m%d%H%M%S")) + str(random.randint(1000,9999))
    return order_num
class OrderView(APIView):
    def post(self, request):
        user = request.data.get('user')
        order = redistoll.getstr(user)
        if order:
            return Response({"message": "订单已存在，请勿重复下单", "code": 400})
        transac = transaction.savepoint()
        try:
            orderdata = {
                'orderno': get_order_num(),
                'user': user,
                'score': int(request.data.get('score', 0)),
                'paytype': int(request.data.get('paytype', 0)),
                'address': int(request.data.get('address',))
            }
            cart = CartModel.objects.filter(user=user, select=True)
            total = 0
            for i in cart:
                total += i.price * i.num
            orderdata['totalprice'] = total
            orderdata['payprice'] = total
            # 计算实际支付的价格
            if orderdata['score'] != 0:
                orderdata['payprice'] = float(orderdata['totalprice']) - orderdata['score'] / 10
            ordser = OrderSerializer(data=orderdata)
            if ordser.is_valid():
                ordser.save()
                for i in cart:
                    detial = {
                        'order': ordser.data.get('id'),
                        'cake': i.cake.id,
                        'price': i.price,
                        'cover': "https://127.0.0.1:8000/uploads" + str(i.cname.cover),
                        'cname': i.cname.kname
                    }
                    detialser = OrderDetialSerializer(data=detial)
                    if detialser.is_valid():
                        detialser.save()
                    else:
                        return Response({'message': detialser.errors, 'code': 400})
                    i.delete()
            else:
                return Response({'message': ordser.errors, 'code': 400})
            redistoll.delstr(user)
            transaction.savepoint_commit(transac)
            return Response({'message': "订单生成成功", 'code': 200, "orderno": orderdata['orderno'], "timeout": 30})
        except IntegrityError as e:
            transaction.savepoint_rollback(transac)
            return Response({'message': f"数据库操作异常: {str(e)}", 'code': 500})
        except Exception as e:
            transaction.savepoint_rollback(transac)
            return Response({'message': f"下单失败: {str(e)}", 'code': 500})


# 生成支付链接的接口
from utils.Alipay import AliPaySDK

class AlipayLink(APIView):
    def get(self, request):
        oid = request.query_params.get('order_id')
        order = OrderModel.objects.filter(orderno=oid).first()
        print(oid)
        if order:
            ali = AliPaySDK()
            return Response(ali.page_pay(order.orderno, order.payprice, '向畅乐芙支付'))
        else:
            return Response({"msg": "订单不存在"})